﻿using System.Windows.Forms;
using Client.Controllers;
using Client.Interfaces;
using Global.Impl.Server;
using Global.Interfaces.Server;
using System;

namespace Client.UserControls
{
    internal partial class BuddyList : UserControl, IBuddyListView
    {
        private IBuddyListController _controller;

        internal BuddyList(IMainController main)
        {
            InitializeComponent();

            _controller = new BuddyListController(main, this);

            // Add root node
            this.tBuddyList.Nodes.Add(new TreeNode("Users"));
        }

        private void tBuddyList_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            var b = e.Node.Tag as IBuddy;
            if (b != null)
                _controller.StartChat(b);
        }

        #region IBuddyListView Members

        public void AddBuddyToList(IBuddy buddy)
        {
            var t = new TreeNode(buddy.Username + ", " + buddy.Ip + ":" + buddy.Port.ToString() + " (" + (buddy.IsOnline ? "Online" : "Offline") + ")");
            t.Tag = buddy;

            MethodInvoker invoker = delegate
            {
                TreeNode root = this.tBuddyList.Nodes[0];
                root.Nodes.Add(t);
            };
            if (!this.IsDisposed)
                this.Invoke(invoker);
        }

        public void ClearBuddyList()
        {
            MethodInvoker invoker = delegate
            {
                TreeNode root = this.tBuddyList.Nodes[0];
                root.Nodes.Clear();
            };
            if (!this.Disposing && !this.IsDisposed)
                this.Invoke(invoker);
        }

        #endregion

        private void tBuddyList_ItemDrag(object sender, ItemDragEventArgs e)
        {
            TreeNode node = e.Item as TreeNode;
            if (node != null)
                DoDragDrop(node, DragDropEffects.Copy);
        }

        private void tBuddyList_DragEnter(object sender, DragEventArgs e)
        {
            e.Effect = DragDropEffects.Copy;
        }
    }
}
